package com.fxcalibre.fxml.control;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import com.fxcalibre.db.beans.Person;
import com.fxcalibre.fxml.view.FXMLViewLoader;
import com.fxcalibre.hibernate.dao.PeopleDAO;
import com.fxcalibre.utils.Constants;

public class SelectPerson extends VBox
{
	@FXML
	TableView<Person> peopleTable;
	@FXML
	ComboBox<String> role;
	@FXML
	private TableColumn<Person, String> nameColumn;
	ObservableList<Person> tableData = FXCollections.observableArrayList(PeopleDAO.getPeople());

	Person selectedPerson;
	String selectedRole;
	Stage dialogStage;

	public SelectPerson()
	{
		FXMLViewLoader.load(this, "SelectPerson.fxml");

		peopleTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		peopleTable.setItems(tableData);
		nameColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("name"));

		// Listen for selection changes
		peopleTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Person>()
		{
			@Override
			public void changed(ObservableValue<? extends Person> observable, Person oldValue, Person newValue)
			{
				selectedPerson = newValue;
			}
		});
		role.getItems().addAll(Constants.roles);
		role.getSelectionModel().select(Constants.roles[0]);
	}

	@FXML
	protected void selectAndClose(ActionEvent event)
	{
		selectedRole = role.getSelectionModel().getSelectedItem();
		dialogStage.close();
	}

	public void showInStage()
	{
		dialogStage = new Stage();
		dialogStage.setTitle("Edit Media");
		dialogStage.initModality(Modality.APPLICATION_MODAL);
		Scene scene = new Scene(this);
		dialogStage.setScene(scene);
		dialogStage.sizeToScene();
		dialogStage.showAndWait();
	}

	public Person getSelectedPerson()
	{
		return selectedPerson;
	}

	public String getSelectedRole()
	{
		return selectedRole;
	}

	public void setSelectedPerson(Person selectedPerson)
	{
		this.selectedPerson = selectedPerson;
	}

}
